package com.shycloud.mido.homework.sharding;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import lombok.extern.slf4j.Slf4j;


/**
 * @author Xiaoxing Yu
 * @date 2020/11/19 下午1:38
 **/
@Slf4j
public class HomeworkMainComplexShardingAlgorithm implements ComplexKeysShardingAlgorithm {

	/**
	 * @param actualTableNames	在加载配置文件时，会解析表分片规则。将结果存储到 collection中，doSharding（）参数使用
	 * @param complexKeysShardingValue	SQL中对应的列的数据
	 * @return java.util.Collection<java.lang.String>
	 * @author xiaoxing.yu
	 * @date 2020/11/19 下午2:11
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Collection<String> doSharding(Collection actualTableNames, ComplexKeysShardingValue complexKeysShardingValue) {
		System.out.println("collection:" + actualTableNames + ",shardingValues:" + complexKeysShardingValue);

		// 返回真实表名集合
		List<String> tableNameList = new ArrayList<>();

		// 逻辑表名
		String logicTableName = complexKeysShardingValue.getLogicTableName();

		// 分片键的值
		Collection<String> teacherIdValues = (Collection<String>) complexKeysShardingValue
																.getColumnNameAndShardingValuesMap().get("teacher_id");


		Collection<String> studentIdValues = (Collection<String>) complexKeysShardingValue
																	.getColumnNameAndShardingValuesMap().get("student_id");
		if (CollectionUtils.isEmpty(teacherIdValues) || CollectionUtils.isEmpty(studentIdValues)) {
			if (Objects.nonNull(actualTableNames)) {
				for (String tableName : (Collection<String>) actualTableNames) {
						tableNameList.add(tableName);
				}
			}
		}else {
			// 获取真实表名
			for (String teacherId : teacherIdValues) {
				for (String studentId : studentIdValues) {
//					String tableSuffix = teacherId + "_0" + Math.abs(studentId) % 8;
					String tableSuffix = String.valueOf(
							new ConsistentHashSharding().getInstance().get(teacherId + studentId) % actualTableNames.size());

					for (String tableName : (Collection<String>) actualTableNames) {
						if (tableName.endsWith(tableSuffix)) {
							tableNameList.add(tableName);
						}
					}
				}
			}
		}
		 

		return tableNameList;
	}

//	/**
//	 * 例如: SELECT * FROM T_ORDER user_id = 100000 AND order_id = 1000009
//	 * 循环 获取SQL 中 分片键列对应的value值
//	 * @param shardingValues sql 中分片键的value值   -> 1000009
//	 * @param key 分片键列名                        -> user_id
//	 * @return shardingValues 集合                 -> [1000009]
//	 */
//	private Collection<Integer> getShardingValue(Collection<ShardingValue> shardingValues, final String key) {
//		Collection<Integer> valueSet = new ArrayList<>();
//		Iterator<ShardingValue> iterator = shardingValues.iterator();
//		while (iterator.hasNext()) {
//			ShardingValue next = iterator.next();
//			if (next instanceof ListShardingValue) {
//				ListShardingValue value = (ListShardingValue) next;
//				// user_id，order_id分片键进行分表
//				if (value.getColumnName().equals(key)) {
//					return value.getValues();
//				}
//			}
//		}
//		return valueSet;
//	}
}
